import React from "react";
import type { FormProps } from "antd";
import { Button, Checkbox, Form, Input, message } from "antd";
import { useNavigate } from "react-router-dom";

import "./index.scss";
import { getUserById, requestLogin, requestRegister } from "../../api/register";

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};

const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
  console.log("Success:", values);
};

const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (errorInfo) => {
  console.log("Failed:", errorInfo);
};

const Register: React.FC = () => {
  // const router = useRouter();

  const [uesrForm] = Form.useForm();

  const navigate = useNavigate();

  const getRegister = async () => {
    const form = uesrForm.getFieldsValue();
    const res = await requestRegister(form);

    if (res?.success) {
      const result = await requestLogin({ userId: form.name });

      if (typeof result == 'string') {
        message.success("登陆成功");
        navigate("/create");
      }
    }
  };

  const handleLogin = async () => {
 
    const form = uesrForm.getFieldsValue();
    const resUser = await getUserById(form.name);

    // 查看用户是否存在，存在就登录，不存在就注册
    console.log("resUser", resUser);
    if (resUser?.success) {
      const result = await requestLogin({ userId: form.name });
      console.log(result,'result')
      if (typeof result == 'string') {
        message.success("登陆成功");
        navigate("/create");
      }

      return;
    }

    // 不存在就走注册流程
    getRegister();
  };

  return (
    <div className="block">
      <Form
        form={uesrForm}
        className="blockForm"
        name="basic"
        layout="vertical"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          name="name"
          rules={[{ required: true, message: "请输入用户名" }]}
        >
          <Input className="input" placeholder="请输入用户名" />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[{ required: true, message: "请输入密码" }]}
        >
          <Input.Password className="input" placeholder="请输入密码" />
        </Form.Item>

        <Form.Item name="remember" valuePropName="checked">
          <Checkbox>记住我</Checkbox>
        </Form.Item>

        <Form.Item>
          <Button
            className="button"
            type="primary"
            htmlType="submit"
            // color="#b9c3f4"
            onClick={handleLogin}
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Register;
